<?php

class Consignee_model extends CI_Model {

    function ConsigneeModel() {
        parent::Model();
    }

    function add() {
        $return = array();
        if ($this->_checkAvailableInStock()) {
            $this->db->insert('Consignee', array(
                'official_order_id' => check_post('official-order'),
                'date' => $this->db->convertDate(check_post('date')),
                'consignee_name' => check_post('consignee'),
                'note' => check_post('note')
            ));
        } else {
            $return['result'] = false;
            $return['message'] = 'មេដាយក្នុងស្តុក មិនគ្រប់គ្រាន់សំរាប់បញ្ចេញ';
            return $return;
        }
        if ($this->db->affected_rows() > 0) {
            $return = $this->addMedal($this->db->insert_id());
        } else {
            $return['result'] = false;
            $return['message'] = 'ទិន្នន័យមិនអាចរក្សារទុកបាន';
        }
        return $return;
    }

    function update() {

        $return = array();
        $this->db->where('ID', check_post("offerid"));
        $this->db->update('Consignee', array(
            'official_order_id' => check_post('official-order'),
            'date' => $this->db->convertDate(check_post('date')),
            'consignee_name' => check_post('consignee'),
            'note' => check_post('note')
        ));
        if ($this->db->affected_rows() > 0) {
            $return['result'] = true;
            $return['message'] = 'ទិន្នន័យបានរក្សារទុក';
        }
//        $return = $this->updateMedal(check_post("offerid"));
        return $return;
    }

    function addMedal($id) {
        // Add Medal for offer
        $medals = $_POST['medal'];
        foreach ($medals as $typeId => $classes) {
            if (is_array($classes)) {
                foreach ($classes as $classId => $value) {
                    $medalID = $this->getMedalID($typeId, $classId);
                    $this->db->query("UPDATE Medal_Stock SET amount = amount - {$value} WHERE medal_ID = {$medalID}");
                    $this->updateOfferSummary($medalID, $value);
                    $this->db->insert('Medal_Consignee', array(
                        'consignee_ID' => $id,
                        'medal_ID' => $medalID,
                        'amount' => $value
                    ));
                }
            } else {
                $medalID = $this->getMedalID($typeId);
                $this->db->query("UPDATE Medal_Stock SET amount = amount - {$classes} WHERE medal_ID = {$medalID}");
                    $this->updateOfferSummary($medalID, $classes);
                $this->db->insert('Medal_Consignee', array(
                    'consignee_ID' => $id,
                    'medal_ID' => $medalID,
                    'amount' => $classes
                ));
            }
        }
        $return['result'] = true;
        $return['message'] = 'ទិន្នន័យបានរក្សារទុក';
        return $return;
    }

    function updateOfferSummary($medalID, $amount) {
        $q = $this->db->get_where('offer_summary', array('medal_id' => $medalID));
        if ($q->num_rows() > 0) {
            $this->db->query("UPDATE offer_summary SET amount = amount + {$amount} WHERE medal_id = {$medalID}");
        }else{
            $this->db->insert("offer_summary", array(
                "medal_id" => $medalID,
                "amount" => $amount
            ));
        }
    }

    function _checkAvailableInStock() {
        $medals = $_POST['medal'];
        foreach ($medals as $typeId => $classes) {
            if (is_array($classes)) {
                foreach ($classes as $classId => $value) {
                    $medalID = $this->getMedalID($typeId, $classId);
                    $q = $this->db->get_where('Medal_Stock', array('medal_ID' => $medalID, "amount <" => $value));
                    if ($q->num_rows() > 0) {
                        return false;
                    }
                }
            } else {
                $medalID = $this->getMedalID($typeId);
                $q = $this->db->get_where('Medal_Stock', array('medal_ID' => $medalID, "amount <" => $classes));
                if ($q->num_rows() > 0) {
                    return false;
                }
            }
        }
        return true;
    }

    function updateMedal($id) {
        // Update Medal for offer
        $medals = $_POST['medal'];
        foreach ($medals as $typeId => $classes) {
            if (is_array($classes)) {
                foreach ($classes as $classId => $value) {
                    $medalID = $this->getMedalID($typeId, $classId);
                    $this->db->update('Medal_Consignee', array('amount' => $value), array(
                        'consignee_ID' => $id,
                        'medal_ID' => $medalID
                    ));
                }
            } else {
                $medalID = $this->getMedalID($typeId);
                $this->db->update('Medal_Consignee', array('amount' => $classes), array(
                    'consignee_ID' => $id,
                    'medal_ID' => $medalID
                ));
            }
        }
        $return['result'] = true;
        $return['message'] = 'ទិន្នន័យបានរក្សារទុក';
        return $return;
    }

    function getMedalID($typeID, $classID = null) {
        $this->db->select("ID");
        if (!empty($classID)) {
            $row = $this->db->get_where("Medal", array("Medal_Type_ID" => $typeID, "Medal_Class_ID" => $classID))->result_array();
        } else {
            $row = $this->db->get_where("Medal", array("Medal_Type_ID" => $typeID))->result_array();
        }
        return $row[0]['ID'];
    }

    function get_consignee() {
        $aColumns = array('Consignee.ID', 'Order_Number', 'consignee_name', 'Consignee.date');
        $where = "";

        if (isset($_GET['iSortCol_0'])) {
            for ($i = 0; $i < intval(check_get('iSortingCols')); $i++) {
                if ($_GET['bSortable_' . intval($_GET['iSortCol_' . $i])] == "true") {
                    $this->db->order_by($aColumns[intval($_GET['iSortCol_' . $i])], $_GET['sSortDir_' . $i]);
                }
            }
        } else {
            $this->db->order_by("Consignee.ID", "ASC");
        }
        $order = $this->db->ar_orderby;

        if ($_GET['sfrom'] != '' && strpos($_GET['sfrom'], '/')) {
            $where .= $where != "" ? " AND " : " ";
            $where .= " Consignee.date >= '" . $this->db->convertDate(check_get('sfrom')) . "'";
            ;
        }
        if ($_GET['sto'] != '' && strpos($_GET['sto'], '/')) {
            $where .= $where != "" ? " AND " : " ";
            $where .= " Consignee.date <= '" . $this->db->convertDate(check_get('sto')) . "'";
        }
        if ($_GET['sofficial-order'] != '') {
            $where .= $where != "" ? " AND " : " ";
            $where .= " Consignee.official_order_id = " . check_get('sofficial-order');
        }

        if ($_GET['smedaltype'] != '') {
//            $where .= $where != "" ? " AND " : " ";
//            $where .= " Consignee.official_order_id = " . check_get('smedaltype');
        }

        if ($where != "") {
            $this->db->where($where);
        }

        $this->db->select('Consignee.ID');
        $this->db->join('Official_Order', 'Official_Order.ID= Consignee.official_order_id', 'inner');
        $totalQuery = $this->db->get('Consignee');
        if ($where != "") {
            $this->db->where($where);
        }

        $this->db->select('Consignee.ID, Official_Order.Order_Number, Consignee.consignee_name, Consignee.date');
        $this->db->join('Official_Order', 'Official_Order.ID= Consignee.official_order_id', 'inner');
        $query = $this->db->get('Consignee', check_get('iDisplayStart'), check_get('iDisplayLength'), $order);
        $consignees = $query->result_array();
        $aaData = array();
        $i = check_get('iDisplayStart');
        foreach ($consignees as $consignee) {
            $data = array(++$i, $consignee['Order_Number'], $consignee['consignee_name'], date("d/m/Y", strtotime($consignee['date'])), "<a class='edit-btn edit-offer' title='កែប្រែ' rel='{$consignee['ID']}'>&nbsp;</a>");
//            $data = array(++$i, $consignee['Order_Number'], $consignee['consignee_name'], date("d/m/Y", strtotime($consignee['date'])), "<a class='edit-btn edit-offer' title='កែប្រែ' rel='{$consignee['ID']}'>&nbsp;</a>", "<a class='delete-btn delete-offer' rel='{$consignee['ID']}' title='លុប'>&nbsp;</a>");
            array_push($aaData, $data);
        }

        $output = array(
            "sEcho" => intval(!empty($_GET['sEcho']) ? $_GET['sEcho'] : ""),
            "iTotalRecords" => $query->num_rows(),
            "iTotalDisplayRecords" => $totalQuery->num_rows(),
            "aaData" => $aaData
        );
        return $output;
    }

}

?>
